#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: sourceview.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  a customized gtksourceview widget for vazaar

import os, os.path
import sys
import gtk
import gtksourceview2 as gtksourceview
import gio
import pango

from vazaarlib.constants import VAZAAR_USER_RESOURCES_DIR

class SourceView(gtk.ScrolledWindow):
    def __init__(self, file=None, data=None):
        gtk.ScrolledWindow.__init__(self)
        if os.path.exists(file):
            self.path = file
        else:
            file = VAZAAR_USER_RESOURCES_DIR + '/' + file
            if os.path.exists(file):
                self.path = file
            else:
                return

        self.data = data

        # create buffer
        self.buffer = gtksourceview.Buffer()
        self.mgr = gtksourceview.style_scheme_manager_get_default()
        self.style_scheme = self.mgr.get_scheme('classic')
        if self.style_scheme:
            self.buffer.set_style_scheme(self.style_scheme)

        # view
        self.view = gtksourceview.View(self.buffer)
        #buffer.connect('mark-set', move_cursor_cb, view)
        #buffer.connect('changed', update_cursor_position, view)
        #view.connect('button-press-event', button_press_cb)

        self.set_shadow_type(gtk.SHADOW_NONE)
        self.add(self.view)

        # setup view
        self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        font_desc = pango.FontDescription('monospace')
        if font_desc:
            self.view.modify_font(font_desc)

        self.load_file()
        self.show_all()

    def get_language_for_mime_type(self, mime):
        lang_manager = gtksourceview.language_manager_get_default()
        lang_ids = lang_manager.get_language_ids()
        for i in lang_ids:
            lang = lang_manager.get_language(i)
            for m in lang.get_mime_types():
                if m == mime:
                    return lang
        return None


    def remove_all_marks(self):
        begin, end = self.buffer.get_bounds()
        self.marks = self.buffer.remove_source_marks(begin, end)


    def load_file(self):
        self.buffer.begin_not_undoable_action()
        f = gio.File(self.path)
        info = f.query_info("*")
        self.mime_type = info.get_content_type()
        self.language = None

        if self.mime_type:
            self.language = self.get_language_for_mime_type(self.mime_type)
            if not self.language:
                pass
                #print 'No language found for mime type "%s"' % self.mime_type
        else:
            print 'Couldn\'t get mime type for file "%s"' % self.path

        self.buffer.set_language(self.language)
        self.buffer.set_highlight_syntax(True)
        self.remove_all_marks()
        # TODO: use g_io_channel when pygtk supports it
        try:
            self.txt = open(self.path).read()
        except:
            return False
        self.buffer.set_text(self.txt)
        self.buffer.set_data('filename', self.path)
        self.buffer.end_not_undoable_action()

        self.buffer.set_modified(False)
        self.buffer.place_cursor(self.buffer.get_start_iter())
        return True

if __name__ == '__main__':
    sv = SourceView('/path/to/filename')
    w = gtk.Window()
    w.add(sv)
    w.show_all()
    w.connect('delete-event', gtk.main_quit)
    gtk.main()

